package com.example.teaculture.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.SearchView;

import com.example.teaculture.R;
import com.example.teaculture.adapter.TeaBaseAdapter;
import com.example.teaculture.application.MyApplication;
import com.example.teaculture.model.Favor;
import com.example.teaculture.model.Headline;
import com.example.teaculture.model.TeaInfo;
import com.example.teaculture.model.Teaknown;
import com.example.teaculture.tools.DateUtils;
import com.example.teaculture.tools.FilterListener;
import com.example.teaculture.tools.MyAdapter;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class SearchActivity extends Activity {

    private List<TeaInfo> oldList;  //application中的数据
    private List<TeaInfo> newList; //重新筛选的数据

    private SearchView sv_search;
    private ListView lsv_ss;
    private List<String> list = new ArrayList<String>();

    boolean isFilter;
    private MyAdapter adapter = null;
    private Button btn_date;
    DateFormat format = DateFormat.getDateTimeInstance();
    Calendar calendar = Calendar.getInstance(Locale.CHINA);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchbar);

        setViews();// 控件初始化
        setData();// 给listView设置adapter
        setListeners();// 设置监听

        Intent intent = getIntent();
        String text = intent.getStringExtra("text");
        sv_search.setQuery(text, true);
    }

    /**
     * 数据初始化并设置adapter
     */
    private void setData() {
        initData();// 初始化数据

        // 这里创建adapter的时候，构造方法参数传了一个接口对象，这很关键，回调接口中的方法来实现对过滤后的数据的获取
        // 回调方法获取过滤后的数据
        adapter = new MyAdapter(list, this, list -> {
            // 这里可以拿到过滤后数据，所以在这里可以对搜索后的数据进行操作
            Log.e("TAG", "接口回调成功");
            Log.e("TAG", list.toString());
            setItemClick();
        });
        lsv_ss.setAdapter(adapter);
    }

    /**
     * 给listView添加item的单击事件
     * <p>
     * newList 过滤后的数据集
     */
    protected void setItemClick() {
        lsv_ss.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(this, FavorDetailActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.putExtra("url", newList.get(position).getUrl());
            intent.putExtra("title", newList.get(position).getTitle());
            startActivity(intent);
        });
    }

    /**
     * 简单的list集合添加一些测试数据
     */
    private void initData() {
//        list.add("茶");

    }

    private void setListeners() {

        /**
         * 对searchView添加文本改变监听，搜索的具体功能在这里实现
         * 很简单，文本该变的时候进行搜索。关键方法是重写onQueryTextChange（）方法。
         */
        // 设置搜索文本监听
        sv_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            // 当点击搜索按钮时触发该方法
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public boolean onQueryTextSubmit(String query) {
                oldList = MyApplication.getInstance().list;
                newList = new ArrayList<>();
                try {
                    if (DateUtils.validDateEffecitive(query)) {
                        for (int i = 0; i < oldList.size(); i++) {
                            if (oldList.get(i).date.compareTo(query) == 0) {
                                newList.add(oldList.get(i));
                            }
                        }
                    } else {
                        for (int i = 0; i < oldList.size(); i++) {
                            if (oldList.get(i).title.indexOf(query) != -1) {
                                newList.add(oldList.get(i));
                            }
                        }
                        //按日期进行排序
                        newList.sort((t1, t2) -> t2.getDate().compareTo(t1.getDate()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                TeaBaseAdapter teaBaseAdapter = new TeaBaseAdapter(SearchActivity.this, newList);
                lsv_ss.setAdapter(teaBaseAdapter);
                return true;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)) {
                    lsv_ss.setFilterText(newText);
                } else {
                    lsv_ss.clearTextFilter();
                }
                return false;
            }
        });

        btn_date.setOnClickListener(v -> {
            DateUtils.showDatePickerDialog(this, 4, sv_search, calendar);
        });
        setItemClick();

    }

    /**
     * 控件初始化
     */
    private void setViews() {
        sv_search = (SearchView) findViewById(R.id.sv_search);// EditText控件
        lsv_ss = (ListView) findViewById(R.id.search_content_show_ll);// ListView控件
        btn_date = findViewById(R.id.btn_date);
    }

    public void searchbar(View view) {
        this.finish();
    }

}
